package com.example.myapplication;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.View;

import androidx.annotation.Nullable;

import java.util.Random;


public class PlayingIndicator extends View {
    private static final String TAG = PlayingIndicator.class.getSimpleName();


    private Paint mPaint;
    private int lineColor;
    private Handler mHandler;
    private int duration = 0;
    private Random mRandom;
    private int lineWidth = 6;

    public PlayingIndicator(Context context) {
        super(context);
        init();
    }

    public PlayingIndicator(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PlayingIndicator(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    public void setIndicatorColor(int color) {
        lineColor = color;
    }

    private void init() {
        mPaint = new Paint();
        mPaint.setColor(Color.BLACK);
        mPaint.setAntiAlias(true);
        mPaint.setStyle(Paint.Style.FILL);

        mHandler = new Handler();
        mRandom = new Random();
    }


    private class DurationRunnable implements Runnable {

        @Override
        public void run() {
            duration = duration + 10;
            if (duration >= 100) {
                duration = 0;
            }
            mHandler.postDelayed(this, 250);
            invalidate();
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        mHandler.postDelayed(new DurationRunnable(), 250);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, widthMeasureSpec);                //高度等于宽度
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getMeasuredWidth();

        mPaint.setColor(lineColor);
        Rect rect = new Rect();
        rect.left = 0;
        rect.top = 0;
        rect.right = lineWidth;
        rect.bottom = width;


        for (int i = 0; i < 3; i++) {
            rect.top = width - mRandom.nextInt(10) * width / 10;
            int transx = (width - lineWidth * 2) / 3;
            rect.offset(transx, 0);
            canvas.drawCircle((rect.left + rect.right) / 2, rect.top, (rect.right - rect.left) / 2, mPaint);        //绘制顶部圆角
            canvas.drawRect(rect, mPaint);
        }
    }


    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        mHandler.removeCallbacksAndMessages(null);
    }
}
